package com.yswl.pri.picture;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yswl.pri.R;
import com.yswl.pri.common.ToolbarMFragment;
import com.yswl.pri.picture.entry.ImageLoftBean;
import com.yswl.pri.picture.entry.ImageSourceLoftCategory;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import yswl.com.klibrary.base.BaseRecyclerAdapter;
import yswl.com.klibrary.base.BaseViewHolder;
import yswl.com.klibrary.http.CallBack.HttpCallback;
import yswl.com.klibrary.http.okhttp.MDeviceUtil;
import yswl.com.klibrary.util.L;
import yswl.com.klibrary.util.MUrlUtil;

public class PictureListLoftFragment extends ToolbarMFragment implements HttpCallback<String> {
    private static final String TAG = PictureListLoftFragment.class.getSimpleName();
    private static final int LOAD_MORE = 1;
    private static final int REFRESH = 2;
    private static final String ARG_PARAM1 = "param1";

    private ImageSourceLoftCategory mParam1;
    private int currPage = 0;

    public static PictureListLoftFragment newInstance(ImageSourceLoftCategory param1) {
        PictureListLoftFragment fragment = new PictureListLoftFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = (ImageSourceLoftCategory) getArguments().getSerializable(ARG_PARAM1);
        }
    }

    ImagsListAdapterLoft mAdapter;
    RefreshLayout refreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pic_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        //initUI
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(REFRESH);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                loadData(LOAD_MORE);
            }
        });
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        int spanCount = 2;
        if(MDeviceUtil.isTvOrMoble(getMActivity())){
            spanCount = 4;
        }
        GridLayoutManager layoutManager = new GridLayoutManager(getMActivity(), spanCount);
        recyclerView.setLayoutManager(layoutManager);
        SpacesItemDecoration decoration = new SpacesItemDecoration(5);
        recyclerView.addItemDecoration(decoration);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(mContext).resumeRequests();//恢复Glide加载图片
                }else {
                    Glide.with(mContext).pauseRequests();//禁止Glide加载图片
                }
            }
        });
        mAdapter = new ImagsListAdapterLoft(getActivity(), null, R.layout.adapter_image_gride_item);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                //进行列表
                PictureModuleActivity.JumpAct(getMActivity(), mAdapter.getList().get(position));
            }
        });
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        refreshLayout.autoRefresh();
    }

    int urlRes;

    private void loadData(int Mode) {
        if (Mode == LOAD_MORE) currPage++;
        if (Mode == REFRESH) currPage = 1;
        String url = null;
        if (mParam1 == ImageSourceLoftCategory.WY) {
            if (Mode == REFRESH) {
//                if (getRandom() < 50) {
//                    urlRes = R.string.url_loft_yswl;
//                } else {
                    urlRes = R.string.url_loft_meinv;
//                }
            }
            url = MUrlUtil.getUrl(this, urlRes, currPage);
        }
        new MyAsyncTask(Mode).execute(url);

//        HttpClientProxy2.getInstance().getAsyn(url, Mode, null, this);
    }

    class MyAsyncTask extends AsyncTask<String, Void, List<ImageLoftBean>> {
        int requestId;
        public MyAsyncTask(int requestId) {
            this.requestId = requestId;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<ImageLoftBean> doInBackground(String... strings) {
            String url = strings[0];
            try {
                Document document = Jsoup.connect(url).get();
                Elements elements = document.select(".m-post,.photo");
                if (elements == null || elements.size() == 0) {
                    return null;
                }

                List<ImageLoftBean> imgs = new ArrayList<>(elements.size());
                for (int i = 0; i < elements.size(); i++) {
                    ImageLoftBean loft = new ImageLoftBean();
                    Elements elements2 = elements.get(i).select("div > a");
                    if (elements2 != null) {
                        loft.link = elements2.get(0).attr("href");
                    }
                    Elements elements3 = elements.get(i).select("span.img > img");
                    if (elements3 != null) {
                        loft.url = elements3.get(0).attr("src");
                    }

                    loft.count = elements.get(i).select("span.icon").html();
                    imgs.add(loft);
                }
                return imgs;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<ImageLoftBean> lists) {
            super.onPostExecute(lists);

            if (lists != null && lists.size() > 0) {
                if (requestId == REFRESH) {
                    refreshLayout.finishRefresh();
                    mAdapter.setList(lists);
                } else {
                    refreshLayout.finishLoadMore();
                    mAdapter.addList(lists);
                }
                refreshLayout.setEnableLoadMore(true);
            }else {
                if(requestId == REFRESH){
                    refreshLayout.finishRefresh();
                }else {
                    refreshLayout.finishLoadMore();
                }
                refreshLayout.setEnableLoadMore(false);
            }
        }
    }


    private int getRandom() {
        Random random = new Random();
        return random.nextInt(100);
    }

    @Override
    public void onSucceed(int requestId, String result) {
        L.d(TAG, " onSucceed : " + result);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (TextUtils.isEmpty(result)) {
            refreshLayout.setEnableLoadMore(false);
            return;
        }

        Document document = Jsoup.parse(result);
        Elements elements = document.select(".m-post,.photo");
        if (elements == null || elements.size() == 0) {
            refreshLayout.setEnableLoadMore(false);
            return;
        } else {
            refreshLayout.setEnableLoadMore(true);
        }

        List<ImageLoftBean> imgs = new ArrayList<>(elements.size());
        for (int i = 0; i < elements.size(); i++) {
            ImageLoftBean loft = new ImageLoftBean();
            Elements elements2 = elements.get(i).select("div > a");
            if (elements2 != null) {
                loft.link = elements2.get(0).attr("href");
            }
            Elements elements3 = elements.get(i).select("span.img > img");
            if (elements3 != null) {
                loft.url = elements3.get(0).attr("src");
            }

            loft.count = elements.get(i).select("span.icon").html();
            imgs.add(loft);
        }


        if (requestId == REFRESH) {
            mAdapter.setList(imgs);
        } else {
            mAdapter.addList(imgs);
        }
    }

    @Override
    public void onFail(int requestId, String errorMsg) {
        L.e(TAG, " onFail : " + errorMsg);
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(100, false, false);//传入false表示加载失败
    }

    public class ImagsListAdapterLoft extends BaseRecyclerAdapter<ImageLoftBean> {

        public ImagsListAdapterLoft(Context mContext, List<ImageLoftBean> mList, int itemLayoutId) {
            super(mContext, mList, itemLayoutId);
        }

        @Override
        public void onBind(BaseViewHolder holder, ImageLoftBean imag, int position) {
            ImageView imageView = holder.findById(R.id.image);
            L.e(TAG, "img detail url: " + imag.url);
            Glide.with(mContext)
                    .load(imag.url).thumbnail(0.01f)
                    .into(imageView);
        }



    }
}
